//
//  MainCenterBackViewController.m
//  ChireTeacher
//
//  Created by 裴烨烽 on 2019/1/21.
//  Copyright © 2019 炽热教育. All rights reserved.
//

#import "MainCenterBackViewController.h"
// view
#import "PlusingAnnotationView.h"
#import "MapLiverAnnotationView.h"
#import "MapBuilderAnnotationView.h"

// model
#import "MapPointAnnotationModel.h"
#import "MapBuidingAnnotationModel.h"

@interface MainCenterBackViewController ()
@property (nonatomic,strong)NSMutableArray *studentsMutableArr;
@end

@implementation MainCenterBackViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self pageSetting];
    [self arrayWithInit];
    [self mapBaseSetup];
    [self sendRequestToGetStudentLocationList];
    
}

#pragma mark - pageSetting
-(void)pageSetting{
    self.view.backgroundColor = [UIColor whiteColor];
}

-(void)arrayWithInit{
    self.studentsMutableArr = [NSMutableArray array];
}


-(void)mapBaseSetup{
    [self changeMapCompassShow:NO];                                         // 1. 不显示罗盘
    [self changeMapScaleShow:NO];                                           // 1. 不显示比例尺
    [self changeMapTrafficType:NO];                                         // 1. 显示当前交通情况
    [self changeMapTypeWithType:MAMapTypeStandard];                         // 2. 显示当前普通地图
    [self showLocationWithStatus:YES];                                      // 3. 显示当前定位地址
    [self showLocationWithType:MAUserTrackingModeFollow];                   // 3.1 当前定位模式
}


#pragma mark - 显示罗盘
-(void)changeMapCompassShow:(BOOL)isShow{
    self.mapView.showsCompass = isShow;
}

#pragma mark - 显示比例尺
-(void)changeMapScaleShow:(BOOL)isShow{
    self.mapView.showsScale = isShow;
}

#pragma mark - 修改地图类型【标准，卫星，黑夜】
-(void)changeMapTypeWithType:(MAMapType)mapType{
    self.mapView.mapType = mapType;
}

#pragma mark - 修改是否交通
-(void)changeMapTrafficType:(BOOL)show{
    self.mapView.showTraffic = show;
}

#pragma mark - 显示当前定位地址
#pragma mark 定位状态【打开\关闭】
-(void)showLocationWithStatus:(BOOL)isOpen{
    self.mapView.showsUserLocation = isOpen;
}

#pragma mark 定位模式
-(void)showLocationWithType:(MAUserTrackingMode)type{
    [self.mapView setUserTrackingMode:type animated:YES];
}


#pragma mark - 获取当前的大头指针
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation {
    if ([annotation isKindOfClass:[MAUserLocation class]]){         // 【当前的定位地址】
        static NSString *annotationIdentifyWithOne = @"annotationIdentifyWithOne";
        PlusingAnnotationView *annotaionView = (PlusingAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:annotationIdentifyWithOne];
        if (!annotaionView){
            annotaionView = [[PlusingAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationIdentifyWithOne];
        }
        return annotaionView;
    } else if([annotation isKindOfClass:[MapBuidingAnnotationModel class]]){
        static NSString *reuseIndetifier = @"annotationReuseIndetifierThr";
        MapBuilderAnnotationView *annotationView = (MapBuilderAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
        if (annotationView == nil) {
            annotationView = [[MapBuilderAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
        }
        MapBuidingAnnotationModel *infoAnnotation = (MapBuidingAnnotationModel *)annotation;
        annotationView.transferMainCenterModel = infoAnnotation.transferCenterModel;
        annotationView.canShowCallout= NO;       //设置气泡可以弹出，默认为NO
        annotationView.draggable = YES;        //设置标注可以拖动，默认为NO
        __weak typeof(self)weakSelf = self;
      
        
        [annotationView actionSelectedBlock:^(BOOL selected) {
            if (!weakSelf){
                return ;
            }
            __strong typeof(weakSelf)strongSelf = weakSelf;
            if (selected){
                //在地图上添加圆
                [strongSelf.mapView addOverlay:infoAnnotation.circle];
            } else {
                [strongSelf.mapView removeOverlay:infoAnnotation.circle];
            }
        }];
        
        return annotationView;
        
    }
    return nil;
}


- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id <MAOverlay>)overlay {
    if ([overlay isKindOfClass:[MACircle class]]) {
        MACircleRenderer *circleRenderer = [[MACircleRenderer alloc] initWithCircle:overlay];
        
        circleRenderer.lineWidth    = 2.f;
        circleRenderer.strokeColor  = [UIColor colorWithCustomerName:@"地图灰"];
        circleRenderer.fillColor =       [UIColor colorWithCustomerName:@"地图蓝"];
        return circleRenderer;
    }
    return nil;
}


#pragma mark - 点击方法
- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view {
    if ([view isKindOfClass:[MapLiverAnnotationView class]]){
        MapLiverAnnotationView *cusView = (MapLiverAnnotationView *)view;
        CGRect frame = [cusView convertRect:cusView.calloutView.frame toView:self.mapView];

        frame = UIEdgeInsetsInsetRect(frame, UIEdgeInsetsMake(kCalloutViewMargin, kCalloutViewMargin, kCalloutViewMargin, kCalloutViewMargin));

        if (!CGRectContainsRect(self.mapView.frame, frame)) {
            /* Calculate the offset to make the callout view show up. */
            CGSize offset = [self offsetToContainRect:frame inRect:self.mapView.frame];

            CGPoint screenAnchor = CGPointMake(10, 10);
            CGPoint theCenter = CGPointMake(self.mapView.bounds.size.width * screenAnchor.x, self.mapView.bounds.size.height * screenAnchor.y);
            theCenter = CGPointMake(theCenter.x - offset.width, theCenter.y - offset.height);

            CLLocationCoordinate2D coordinate = [self.mapView convertPoint:theCenter toCoordinateFromView:self.mapView];

            [self.mapView setCenterCoordinate:coordinate animated:YES];
        }
    }
}

- (CGSize)offsetToContainRect:(CGRect)innerRect inRect:(CGRect)outerRect {
    CGFloat nudgeRight = fmaxf(0, CGRectGetMinX(outerRect) - (CGRectGetMinX(innerRect)));
    CGFloat nudgeLeft = fminf(0, CGRectGetMaxX(outerRect) - (CGRectGetMaxX(innerRect)));
    CGFloat nudgeTop = fmaxf(0, CGRectGetMinY(outerRect) - (CGRectGetMinY(innerRect)));
    CGFloat nudgeBottom = fminf(0, CGRectGetMaxY(outerRect) - (CGRectGetMaxY(innerRect)));
    return CGSizeMake(nudgeLeft ?: nudgeRight, nudgeTop ?: nudgeBottom);
}





#pragma mark - 执行方法
//-(void)showActionManagerWithUser:(OtherSearchSingleModel *)userModel{
//    __weak typeof(self)weakSelf = self;
//    [[UIActionSheet actionSheetWithTitle:@"查看详情" buttonTitles:@[@"取消",@"去这里",@"查看详情"] callback:^(UIActionSheet *actionSheet, NSInteger buttonIndex) {
//        if (!weakSelf){
//            return ;
//        }
//        __strong typeof(weakSelf)strongSelf = weakSelf;
//        if (buttonIndex == 0){
//            [strongSelf showMapWithManager:userModel];
//        } else if (buttonIndex == 1){               // 查看详情
//            UserInfoViewController *userInfoViewController = [[UserInfoViewController alloc]init];
//            userInfoViewController.transferSearchSingleModel = userModel;
//            [strongSelf.transferMenuController.navigationController pushViewController:userInfoViewController animated:YES];
//        } else if (buttonIndex == 2){               // 查看详情
//            NSLog(@"取消");
//        }
//    }]showInView:self.view];
//}
//
//#pragma mark - 执行方法
//-(void)showActionManagerWithBuild:(MapBuildSingleModel *)buildModel{
//    __weak typeof(self)weakSelf = self;
//    [[UIActionSheet actionSheetWithTitle:@"查看详情" buttonTitles:@[@"取消",@"去这里"] callback:^(UIActionSheet *actionSheet, NSInteger buttonIndex) {
//        if (!weakSelf){
//            return ;
//        }
//        __strong typeof(weakSelf)strongSelf = weakSelf;
//        if (buttonIndex == 0){
//            MMHLocationNavigationManager *locationNav = [[MMHLocationNavigationManager alloc]init];
//            [locationNav showActionSheetWithView:strongSelf.view shopName:buildModel.name shopLocationLat:buildModel.lng shopLocationLon:buildModel.lat];
//        } else if (buttonIndex == 1){               // 查看详情
//            //            BuildDetailViewController *buildDetailViewController = [[BuildDetailViewController alloc]init];
//            //            buildDetailViewController.transferBuildSingleModel = buildModel;
//            //            [strongSelf.transferMenuController.navigationController pushViewController:buildDetailViewController animated:YES];
//        } else if (buttonIndex == 2){               // 查看详情
//            NSLog(@"取消");
//        }
//    }]showInView:self.view];
//}
//
//-(void)showMapWithManager:(OtherSearchSingleModel *)userModel{
//    MMHLocationNavigationManager *locationNav = [[MMHLocationNavigationManager alloc]init];
//    [locationNav showActionSheetWithView:self.view shopName:userModel.nick shopLocationLat:userModel.lat shopLocationLon:userModel.lng];
//}


#pragma mark - Interface
-(void)sendRequestToGetStudentLocationList{
    __weak typeof(self)weakSelf = self;
    [[NetworkAdapter sharedAdapter] fetchWithPath:wechat_location_list requestParams:nil responseObjectClass:[MainCenterListModel class] succeededBlock:^(BOOL isSucceeded, id responseObject, NSError *error) {
        if (!weakSelf){
            return ;
        }
        __strong typeof(weakSelf)strongSelf = weakSelf;
        if (isSucceeded){
            MainCenterListModel *centerListModel = (MainCenterListModel *)responseObject;
            [strongSelf reloadMapWithList:centerListModel];
        }
    }];
}


-(void)reloadMapWithList:(MainCenterListModel *)centerListModel{
    if (!self.studentsMutableArr){
        self.studentsMutableArr = [NSMutableArray array];
    } else {
        [self.studentsMutableArr removeAllObjects];
    }
    // 刷新
    NSMutableArray *annotationBuildMutableArr = [NSMutableArray array];
    for (int i = 0 ; i < centerListModel.list.count;i++){
        MainCenterModel *centerModel = [centerListModel.list objectAtIndex:i];
        
        MapBuidingAnnotationModel *pointAnnotation = [[MapBuidingAnnotationModel alloc] init];
        pointAnnotation.transferCenterModel = centerModel;
        pointAnnotation.coordinate = CLLocationCoordinate2DMake([centerModel.lng floatValue],[centerModel.lat floatValue]);
        [annotationBuildMutableArr addObject:pointAnnotation];
        
        // 创建绘图
        MACircle *circle = [MACircle circleWithCenterCoordinate:CLLocationCoordinate2DMake([centerModel.lng floatValue],[centerModel.lat floatValue]) radius:300];
        pointAnnotation.circle = circle;
    }
    [self.mapView addAnnotations:annotationBuildMutableArr];
    [self.mapView showAnnotations:annotationBuildMutableArr animated:NO];
    [self showLocationWithType:MAUserTrackingModeFollow];
}

@end
